﻿using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Forms;

namespace System
{
    public class StopwatchHelper
    {
        private static log4net.ILog _logger = log4net.LogManager.GetLogger("PerformancenLogger");

        private static Dictionary<string, Stopwatch> _watchTable = new Dictionary<string, Stopwatch>();
        private static bool _isFirst = true;
        public static bool IsWriteLog = false;

        public static void Start(string flag)
        {
            if (IsWriteLog && _isFirst)
            {
                _isFirst = false;
                _logger.Debug("*************************");
            }

            Stopwatch stopwatch;
            string tag;
            if (_watchTable.TryGetValue(flag, out stopwatch))
            {
                stopwatch.Restart();
                tag = "restart";
            }
            else
            {
                stopwatch = Stopwatch.StartNew();
                _watchTable[flag] = stopwatch;
                tag = "start";
            }
            if (IsWriteLog)
            {
                _logger.Debug($"Stopwatch {flag} {tag}");
            }
        }

        public static long Stop(string flag, string message = "")
        {
            long result = 0;
            if (_watchTable.TryGetValue(flag, out var stopwatch))
            {
                if (IsWriteLog)
                {
                    _logger.Debug($"Stopwatch {flag} {message} {stopwatch.ElapsedMilliseconds}ms");
                }
                _watchTable.Remove(flag);
                stopwatch.Stop();
                result = stopwatch.ElapsedMilliseconds;
            }
            return result;
        }
    }
}
